from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from utils.response_code import RETCODE

from .models import Area

# Create your views here.


class GetAreasView(View):
    """获取地址列表"""

    def get(self, request):
        parent_id = request.GET.get('area_id')
        # 判断上级ID，若为空，查询省信息
        if parent_id is None:
            # 先去缓存中获取数据
            provinces_list = cache.get('provinces_cache')
            if provinces_list is None:
                # 未从缓存中获取到数据，就先查询数据库，然后放入缓存
                provinces = Area.objects.filter(parent_id=None)

                # 将查询到的对象转换为JSON数据，以供Vue去渲染
                provinces_list = []
                for i in provinces:
                    provinces_list.append({
                        'id': i.id,
                        'name': i.name
                    })
                # 放入缓存
                cache.set('provinces_cache', provinces_list, 30*24*3600)
            return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': provinces_list})
        else:
            # 上级ID不为空，获取市区县信息
            # 先从缓存获取
            sub_list = cache.get('sub_cache_%s' % parent_id)
            if sub_list is None:
                sub_areas = Area.objects.filter(parent_id=parent_id)
                sub_list = []
                for i in sub_areas:
                    sub_list.append({
                        'id': i.id,
                        'name': i.name
                    })
                # 放入缓存
                cache.set('sub_cache_%s' % parent_id, sub_list, 30*24*3600)
            return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': sub_list})
